import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

function request(config) {
  // 1.创建axios实例
  const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000,
  });

  // 2.axios拦截器
  instance.interceptors.request.use(
    function (config) {
      if (store.getters.token) {
        /**
         * 每个请求都携带token令牌
         * ['X-Token']是一个自定义标题键, 请根据实际情况修改
         */
        config.headers["X-Token"] = getToken();
      }
      return config;
    },
    function (error) {
      console.log(error);
      return Promise.reject(error);
    }
  );

  // 2.响应拦截器
  instance.interceptors.response.use(
    function (response) {
      const res = response.data;

      if (res.code !== 20000) {
        Message({
          message: res.message || "Error",
          type: "error",
          duration: 5 * 1000,
        });

        // 50008:非法令牌; 50012:其他客户端登录; 50014:令牌过期;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // 重新登录
          MessageBox.confirm(
            "您已经注销，您可以取消此页面，或重新登录  ",
            "确认注销",
            {
              confirmButtonText: "重新登陆",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            store.dispatch("user/resetToken").then(() => {
              location.reload();
            });
          });
        }
        return Promise.reject(new Error(res.message || "Error"));
      } else {
        return res;
      }
    },
    function (error) {
      console.log("err" + error);
      Message({
        message: error.message,
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(error);
    }
  );
  // 3.发送真正的网路请求
  return instance(config);
}

export default request;
